#include "gametask.h"
#include "httpclient.h"
#include <QMessageBox>
#include "QApplication"
GameTask::GameTask(QWidget *parent):BasePersent(parent)
{
    this->parent = parent;
    checkToken();
    qDebug() << "GameTask=";
}

void GameTask::backgroundTask(int task)
{
    GameManager::getInstantce()->roleTask = task;
    if(qTimer->isActive()){
        return;
    }

    backgroundCon = connect(qTimer, &QTimer::timeout, this, [&](){
        if(  GameManager::getInstantce()->roleTask != ROLE_TASK_NORMAL){

            checkMove();

            //checkHell();
        }
    });
    qTimer->setInterval(1000);
    qTimer->start();
}

void GameTask::stopTask(){
    GameManager::getInstantce()->roleTask = ROLE_TASK_NORMAL;
    GameManager::getInstantce()->isCheckHell = true;
    if(qTimer != nullptr){
        qTimer->stop();
    }
        disconnect(con);
    disconnect(backgroundCon);
}

void GameTask::checkMove()
{
    QPoint qPoint = getRolesPoint();
    GameManager::getInstantce()->isMove = (qPoint != qPrePoint || qPoint.isNull());
    qPrePoint = qPoint;
}


void GameTask::callBack(QString str){
    GameManager::getInstantce()->isCheckHell = false;
    emit isHell();
}

bool GameTask::isCancelTask()
{

}

void GameTask::checkHell()
{
    checkDeal(this);
}

void GameTask::checkToken()
{
    if(checkTokenTimer->isActive()){
        return;
    }
    connect(checkTokenTimer, &QTimer::timeout, this, [=](){

        HttpClient(AUTH_CODE_INFO).success([=](const QString &response) {
            qDebug() << response;
            AuthCodeInfoBean authCodeInfo;
            AuthCodeInfoBean::jsonToObject(response.toLatin1(), authCodeInfo);
            netCallBack(authCodeInfo);
        }).param("token", GameManager::getInstantce()->token)
                .param("time",QString::number(QDateTime::currentMSecsSinceEpoch()))
                .post();

    });
    checkTokenTimer->setInterval(600000);
    checkTokenTimer->start();
}

void GameTask::netCallBack(AuthCodeInfoBean authCodeInfo)
{
    if(authCodeInfo.code == SUCCESS){
        GameManager::getInstantce()->invalidTime = authCodeInfo.data.invalidTime;
    }else if(authCodeInfo.code == TOKEN_INVALID){
        stopTask();
        if(QMessageBox::warning(parent,"系统提示", "卡密已失效或在其他地方使用",QMessageBox::Ok)){
            QApplication::exit(0);
        }
    }
}



GameTask::~GameTask()
{
    if(qTimer != nullptr){
        delete qTimer;
        qTimer = nullptr;
    }

    if(checkTokenTimer != nullptr){
        delete checkTokenTimer;
        checkTokenTimer = nullptr;
    }

    stopTask();
    qDebug() << "GameTask析构函数";
}

